package com.xu.t1.common;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * 通用redis缓存工具类
 *
 * @author xu
 *
 */

@Component
public class RedisCache {

    private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();

    //设置缓存，带过期时间，单位秒
    public <T> void set(String key, T value, long expireSeconds) {
        try {
            String json = objectMapper.writeValueAsString(value);
            ValueOperations<String, String> ops = redisTemplate.opsForValue();
            ops.set(key, json, Duration.ofSeconds(expireSeconds));
        } catch (Exception e) {
            logger.error("redis读取失败", e);
        }
    }


    //获取缓存，指定泛型类型
    public <T> T get(String key, TypeReference<T> typeReference) {
        try {
            ValueOperations<String, String> ops = redisTemplate.opsForValue();
            String json = ops.get(key);
            if (json == null) {
                return null;
            }
            return objectMapper.readValue(json, typeReference);
        } catch (Exception e) {
            logger.error("redis读取失败", e);
            return null;
        }
    }

    //简单获取缓存
    public String get(String key) {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        return ops.get(key);
    }

    //删除缓存
    public void delete(String key) {
        redisTemplate.delete(key);
    }
}